// src/services/socketService.js
const Message = require('../models/Message');
const { logger } = require('../utils/logger');

/**
 * 初始化Socket.IO事件
 * @param {Object} io - Socket.IO实例
 */
exports.initSocket = (io) => {
  io.on('connection', (socket) => {
    logger.info(`User connected: ${socket.id}`);

    // 加入聊天室
    socket.on('joinRoom', ({ roomId, userId }) => {
      socket.join(roomId);
      socket.to(roomId).emit('message', {
        userId: 'system',
        text: `${userId} joined the room`,
        timestamp: new Date().toISOString()
      });
      logger.info(`${userId} joined room ${roomId}`);
    });

    // 发送消息
    socket.on('sendMessage', async ({ roomId, userId, text }) => {
      try {
        const message = new Message({
          from: userId,
          to: roomId,
          scene: 'p2p', // 后续支持group
          type: 'text',
          content: text,
          timestamp: new Date()
        });
        await message.save();
        io.to(roomId).emit('message', {
          userId,
          text,
          timestamp: message.timestamp.toISOString(),
          messageId: message._id
        });
        logger.info(`Message sent from ${userId} to ${roomId}`);
      } catch (err) {
        logger.error('Socket send message error:', err);
      }
    });

    // 断开连接
    socket.on('disconnect', () => {
      logger.info(`User disconnected: ${socket.id}`);
    });
  });
};